package me.lc;

import java.text.DecimalFormat;
import java.util.HashMap;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

/**
 * 
 * @author Administrator
 * 
 */
public class SoundManager
{
	public static SoundManager instance = new SoundManager();

	private SoundPool soundPool;
	private HashMap<Integer, Integer> soundPoolMap;
	private AudioManager audioManager;
	private Context context;

	public Context getContext()
	{
		return context;
	}

	public void setContext(Context context)
	{
		this.context = context;
	}

	private SoundManager()
	{

	}

	public void setVolume(float value)
	{
		try
		{
			if (audioManager == null)
			{
				audioManager = (AudioManager) context
						.getSystemService(Context.AUDIO_SERVICE);
			}
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
					(int) (value * audioManager
							.getStreamMaxVolume(AudioManager.STREAM_MUSIC)),
					AudioManager.FLAG_PLAY_SOUND);
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public float getVolume()
	{
		try
		{
			if (audioManager == null)
			{
				audioManager = (AudioManager) context
						.getSystemService(Context.AUDIO_SERVICE);
			}

			float streamVolume = audioManager
					.getStreamVolume(AudioManager.STREAM_MUSIC);
			return streamVolume
					/ audioManager
							.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		} catch (Exception e)
		{
			e.printStackTrace();
			return 0.5f;
		}

	}

	public void init(Context context)
	{
		try
		{
			this.context = context;
			soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 100);
			soundPoolMap = new HashMap<Integer, Integer>();
			DecimalFormat format = new DecimalFormat("00");
			for (int i = 0; i < 30; i++)
			{
				int pId = context.getResources().getIdentifier(
						"p" + format.format(i + 1), "raw",
						context.getPackageName());
				addSound(i, pId);
			}
			audioManager = (AudioManager) context
					.getSystemService(Context.AUDIO_SERVICE);
		} catch (Exception e)
		{
			e.printStackTrace();
		}

	}

	public void playSound(int index)
	{
		try
		{
			float streamVolume = audioManager
					.getStreamVolume(AudioManager.STREAM_MUSIC);
			streamVolume = streamVolume
					/ audioManager
							.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
			soundPool.play(soundPoolMap.get(index), streamVolume, streamVolume,
					10, 0, 1f);
		} catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}

	private void addSound(int index, int SoundID)
	{
		try {
			soundPoolMap.put(index, soundPool.load(context, SoundID, 1));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
